package com.cx.util.jdbc;

import com.cx.pojo.User;
import org.junit.After;
import org.junit.Test;

import java.io.PrintWriter;
import java.sql.*;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.util.jdbc
 * @Description:
 * @Date 2025/6/5 14:06
 */

public class JDBCMethods {

    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    Connection connection = JDBCPoolUtils.getConnection();

    public static void main(String[] args) {
        JDBCMethods jdbcMethods = new JDBCMethods();
        User user = new User();
        user.setName("张士大夫");
        user.setAge(20);
        user.setGender("男");
        user.setEmail("222@163.com");
        user.setCreate_time(new java.util.Date());
        jdbcMethods.insertUser(user);
    }


    @Test
    public void selectAll() {


        try {
            preparedStatement= connection.prepareStatement("select * from user");
             resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id")
                        + " " + resultSet.getString("name")
                        + " " + resultSet.getInt("age")
                        + " " + resultSet.getString("gender")
                        + " " + resultSet.getString("email")
                        + " " + resultSet.getDate("create_time"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e + "sql执行失败");
        }
       JDBCUtil.close(connection,preparedStatement,resultSet);
    }
    //添加用户信息
    public void insertUser(User user) {
        try {
            preparedStatement = connection.prepareStatement("insert into user (name,age,gender,email,create_time) values (?,?,?,?,?)");
            preparedStatement.setString(1, user.getName());
            preparedStatement.setInt(2, user.getAge());
            preparedStatement.setString(3, user.getGender());
            preparedStatement.setString(4, user.getEmail());
            preparedStatement.setDate(5, new Date(new java.util.Date().getTime()));
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                System.out.println("添加成功");
            }else {
                System.out.println("添加失败");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e+"sql执行失败--新增");
        }
        JDBCUtil.close(connection,preparedStatement);
    }



}